#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 本脚由亁颐堂现任明教教主编写，用于乾颐盾Python课程！
# 教主QQ:605658506
# 亁颐堂官网www.qytang.com
# 教主技术进化论拓展你的技术新边疆
# https://ke.qq.com/course/271956?tuin=24199d8a

from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField

node = Flask(__name__)
# 后续内容与文件上传有关
node.config['SECRET_KEY'] = 'welcome to qytang'  # 配置秘钥,用来产生随机数
node.config['UPLOADED_PHOTOS_DEST'] = './upload'  # 定义上传目录
node.config['WTF_CSRF_ENABLED'] = False  # 关闭CSRF保护
# 后续内容与文件上传有关
photos = UploadSet('photos', IMAGES)
configure_uploads(node, photos)
patch_request_class(node)


# 上传图片文件的form
class UploadForm(FlaskForm):
    photo = FileField(validators=[FileAllowed(photos, u'只能上传图片！'), FileRequired(u'文件未选择！')])
    submit = SubmitField(u'上传')


# 文件上传,为了测试Requests模块上传文件的操作
@node.route('/upload', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        filename = photos.save(form.photo.data)
        file_url = photos.url(filename)
    else:
        file_url = None
    return render_template('upload.html', form=form, file_url=file_url)


if __name__ == "__main__":
    # 运行Flask在host='0.0.0.0', port=80
    node.run(host='0.0.0.0', port=80)